package com.base.cn.platform.os.controller.web.course.play;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.LoginForm;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.cou.play.PlayCourseService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用户播放Controller
 *
 * @author s.li
 * @create 2018-05-30-11:07
 */
@Controller
@RequestMapping("/web/uc/play")
public class WebUserPlayController extends WebBaseController {

    @Autowired
    private CourseCatalogService courseCatalogService;
    @Autowired
    private PlayCourseService playCourseService;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 播放课程
     * @param request
     * @param packageId 套餐ID，普通课程传0
     * @param courseId 被播放的课程ID，如果是套餐则传套餐下的课程ID，如果是普通课程则传课程的ID
     * @param catalogId 目录ID
     * @param  type 用来区分是从大厅课程页面的播放，还是个人中心的课程页面的播放 LOBBY（大厅） PERSON（个人）
     * @return 播放大厅页面
     */
    @RequestMapping("/toPlayCourse")
    public String toPlayCourse(HttpServletRequest request,
                         Model model,
                         @RequestParam(value = "packageId",required = false,defaultValue = "0") BigDecimal packageId,
                         @RequestParam(value = "courseId",required = false,defaultValue = "0") BigDecimal courseId,
                         @RequestParam(value = "catalogId",required = false,defaultValue = "0") BigDecimal catalogId,
                         @RequestParam(value = "type") String type){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        //查找用户是否购买了该课程
        Map<String,Object> courseBuyRecord = playCourseService.getPlayCourseBuyRecord(userId,packageId,courseId);
        Map<String, Object>  userNewPlayRecord = new HashMap<>();
        //判断是否是大厅课程
        if(type.equals("LOBBY")){
            //判断用户是否购买了课程
            if(ObjectUtils.isNotEmpty(courseBuyRecord.get("orderId"))){
                //获取,课程/套餐 id
                BigDecimal  buyCourseId=new BigDecimal(courseBuyRecord.get("courseId").toString());
                BigDecimal courseIdTo = courseId;
                //判断是否是套餐还是课程
                if(courseBuyRecord.get("courseTypeKey").toString().equals(CourseType.COURSE_TYPE_PACKAGE.getKey())){
                    courseIdTo =null;
                }
                if(ObjectUtils.isNotEmpty(catalogId)){
                    userNewPlayRecord = playCourseService.findUserNewPlayRecord(userId, buyCourseId, courseIdTo);
                    if(ObjectUtils.isNotEmpty(userNewPlayRecord)){
                        courseId = new BigDecimal(userNewPlayRecord.get("courseId").toString());
                        catalogId = new BigDecimal(userNewPlayRecord.get("catalogId").toString());
                        //如果是套餐修改默认播放位置
                        if(courseBuyRecord.get("courseTypeKey").toString().equals(CourseType.COURSE_TYPE_PACKAGE.getKey())){
                            List<Map<String,Object>> courseBuyPackageCourseList = (List<Map<String, Object>>) courseBuyRecord.get("courseBuyPackageCourseList");
                            if(ObjectUtils.isNotEmpty(courseBuyPackageCourseList)){
                                for(int i=0;i<courseBuyPackageCourseList.size();i++){
                                    if(new BigDecimal(courseBuyPackageCourseList.get(i).get("courseId").toString()).compareTo(courseId)==0){
                                        courseBuyRecord.put("index",i);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        BigDecimal shareId = courseId;
        if(DataUtil.idIsNotNull(packageId)){
            shareId =packageId;
        }
        StringBuilder shareUrl = new StringBuilder("/mobile/course/info?courseId=");
        if(courseBuyRecord.get("courseTypeKey").toString().equals(CourseType.COURSE_TYPE_LIVE.getKey())){
            shareUrl = new StringBuilder("/mobile/course/liveInfo?courseId=");

        }
        model.addAttribute("mobilePathShare",shareUrl.append(shareId));
        model.addAttribute("courseBuyRecord",courseBuyRecord);
        model.addAttribute("userPlayRecord",userNewPlayRecord);
        model.addAttribute("catalogId",catalogId);
        model.addAttribute("courseId",courseId);
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
        String vlasType = configMap.get("type");
        model.addAttribute("vlasType",vlasType);
        return resultPage("/course/play/user-play");
    }

    /**
     * 加载播放的目录
     * @param courseId 课程ID
     * @return 目录列表
     */
    @RequestMapping("/getPlayCatalog")
    public String getPlayCatalog(Model model,
                                 HttpServletRequest request,
                                 @RequestParam("buyCourseId") BigDecimal buyCourseId,
                                 @RequestParam("courseId") BigDecimal courseId){
        if(DataUtil.idIsNotNull(courseId)){
            BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
            List<Map<String,Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(buyCourseId,userId,courseId,true, false, false, false,true);
            Map<String,Object> buyCourseRecord = courseBuyRecordService.checkUserBuyCourse(userId,buyCourseId);
            if(ObjectUtils.isNotEmpty(buyCourseRecord)){
                model.addAttribute("buyCourse",true);
            }else {
                model.addAttribute("buyCourse",false);
            }
            model.addAttribute("courseCatalogList",courseCatalogList);
        }
        return resultPage("/course/play/play-catalog");
    }

    /**
     * 检查播放
     * @param buyCourseId  课程或套餐ID（购买的课程ID）
     * @param courseId  课程ID
     * @param catalogId 章节id
     * @return 检查结果
     */
    @RequestMapping("/checkPlay")
    @ResponseBody
    public Map<String, Object> checkPlay(HttpServletRequest request,
                                         @RequestParam("buyCourseId") BigDecimal buyCourseId,
                                         @RequestParam("courseId") BigDecimal courseId,
                                         @RequestParam("prevCatalogId") BigDecimal prevCatalogId,
                                         @RequestParam("catalogId") BigDecimal catalogId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        return playCourseService.checkCourseCatalogPlay(buyCourseId,courseId,prevCatalogId, catalogId, userId);
    }

    /**
     * 加载播放页面播放器
     * @param sign 签名
     * @return Map<String,Object>
     */
    @RequestMapping("/loadPlayData")
    @ResponseBody
    public Map<String,Object> loadPlayData(HttpServletRequest request,
                                           @RequestParam("sign") String sign){
        String nickname = webMobileLoginUtil.getNickname(request);
        String userAvatar = webMobileLoginUtil.getAvatar(request);
        BigDecimal loginUserId = webMobileLoginUtil.getLoginUserId(request);
        return playCourseService.loadPlayData(sign, LoginForm.LOGIN_FROM_PC,nickname,userAvatar,loginUserId);
    }

    /**
     *  检查是否购买课程/套餐
     *
     * @param courseId 课程id
     */
    @RequestMapping("/check/buy")
    @ResponseBody
    public Map<String, Object> checkBuy(HttpServletRequest request,
                                        @RequestParam("courseId") BigDecimal courseId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> result = courseBuyRecordService.checkUserBuyCourse(userId,courseId);
        if(ObjectUtils.isNotEmpty(result)){
            return ResultUtil.SUCCESS();
        }
        return ResultUtil.ERROR();
    }
}
